package com.aishua.fire.common;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.aishua.fire.common.exp.DuplicationRequestException;
import com.aishua.fire.common.req.HttpHelper;
import com.aishua.fire.config.init.PermInfo;
import com.aishua.fire.jpa.RequestLogDao;
import com.aishua.fire.jpa.entity.RequestLog;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RequestLogUtil {

	@Autowired
	private RequestLogDao requestLogDao;
	
	private long lastRequestTimestamp;
	
	private List<RequestLog> logs = new ArrayList<RequestLog>();
	
	private Queue<RequestLog> caches = new LinkedList<RequestLog>();
	
	
	public void processRequestLog(HttpServletRequest request,String userName,PermInfo perm) {
		RequestLog reqLog = new RequestLog();
		reqLog.setCreateDate(DateUtil.getCurrentDateStr());
		String requestMethod = request.getMethod();
		reqLog.setRequestMethod(requestMethod);
		reqLog.setRequestUri(request.getRequestURI());
		reqLog.setRequestUrL(request.getRequestURL().toString());
		reqLog.setUserName(userName);
		reqLog.setRemoteAddress(request.getRemoteHost());
		reqLog.setRemoteSessionId(request.getRequestedSessionId());
		reqLog.setPermId(perm.getPermId());
		reqLog.setInterfaceName(perm.getPermDesc());
		
		
		/*StringBuilder body = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String str = null;
		while((str = reader.readLine()) != null){
			body.append(str);
		}*/
		String body = HttpHelper.getBodyString(request);
		reqLog.setBody(body);
		
		logs.add(reqLog);
		//如果logs 数量大于500,则保存到数据库中,或者定时扫描时间大于
		if(logs.size() >500) {
			saveAndClear();
		}
		
		lastRequestTimestamp = System.currentTimeMillis();
		
		
		//幂等性校验-问题
		/*for (RequestLog cache : caches) {
			if(reqLog.getRequestUri().equals(cache.getRequestUri()) && reqLog.getRequestMethod().equals(cache.getRequestMethod())) {
				try {
					Date cacheDate = DateUtil.convertByFormat(cache.getCreateDate(), DateUtil.YYYYMMDD_HH_MM_SS);
					if(lastRequestTimestamp - cacheDate.getTime() < 2000) {
						throw new DuplicationRequestException("2秒内重复的请求异常");
					}
				} catch (ParseException e) {
					log.warn("日期时间炸了:{}",e);
				}
			}
		}
		
		
		
		if(caches.size() > 100) {
			//返回第一个元素，并在队列中删除
			caches.poll();
		}
		caches.offer(reqLog);*/
		
	}

	/**
	 * 保存并清空日志缓存
	 */
	public synchronized void saveAndClear() {
		requestLogDao.save(logs);
		logs.clear();
	}
	
	
	public long getLastRequestTimestamp() {
		return lastRequestTimestamp;
	}

	/**
	 * 清除一个月以前的日志记录
	 */
	public void clearOneMonthBefore() {
		// DATEDIFF(t.maintainDate, NOW()) < 15
		requestLogDao.deleteOneMonthBefore();
	}

}
